package org.lwj.Intercepts;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.lwj.Intercepts.crypt.CryptContext;
import org.lwj.common.annotation.CryptField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;

/**
 * 查询拦截器
 * 查询条件加密使用方式：①使用添加注解的实体类作为参数 ②使用 @Param("crypt")注解的自定义类型
 * 返回结果解密使用方式：①在实体类上加上注解 CryptEntity  ②在需要加解密的字段属性上加上CryptField
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class})
})
public class QueryInterceptor implements Interceptor {
    /**
     * 使用 @Param("crypt")注解的参数（只支持自定义对象 且同时添加CryptEntity和CryptField注解）
     */
    public static final String paramVal = "crypt";

    @Resource
    private UpdateInterceptor updateInterceptor;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //获取查询参数，查询条件是否需要加密
        Object[] args = invocation.getArgs();
        Object parameter = args[1];
        Object result = null;
        //设置执行标识
        boolean flag = true;
        if (parameter instanceof MapperMethod.ParamMap) {
            Map paramMap = (Map) parameter;
            if (paramMap.containsKey(paramVal)) {
                Object queryParameter = paramMap.get(paramVal);
                if (updateInterceptor.needToCrypt(queryParameter)) {
                    //执行sql，还原加密后的报文
                    MappedStatement mappedStatement = (MappedStatement) args[0];
                    result = updateInterceptor.proceed(invocation, mappedStatement, queryParameter);
                    flag = false;
                }
            }
        }
        //是否需要执行
        if (flag) {
            result = invocation.proceed();
        }
        if (Objects.isNull(result)) {
            return null;
        }
        // 返回列表数据，循环检查
        if (result instanceof ArrayList) {
            ArrayList resultList = (ArrayList) result;
            if (CollectionUtils.isNotEmpty(resultList) && updateInterceptor.needToCrypt(resultList.get(0))) {
                for (Object resultObject : resultList) {
                    decrypt(resultObject);
                }
            }
        } else if (updateInterceptor.needToCrypt(result)) {
            decrypt(result);
        }
        //返回结果
        return result;
    }


    /**
     * @param resultObject 需要解密的对象
     * @return
     * @throws Exception
     */
    private Object decrypt(Object resultObject) throws Exception {
        // 取出resultType的类
        Class<?> resultCls = resultObject.getClass();
        Field[] fields = resultCls.getDeclaredFields();
        for (Field field : fields) {
            // 获取所有被Sensitive注解的字段
            CryptField cryptAnnotation = field.getAnnotation(CryptField.class);
            if (cryptAnnotation != null) {
                field.setAccessible(true);
                Object obj = field.get(resultObject);
                if (obj instanceof String) {
                    String val = obj.toString();
                    field.set(resultObject, CryptContext.getCrypt(cryptAnnotation.type()).decrypt(val));
                }
            }
        }
        return resultObject;
    }
}